package com.key.puzzlemodel

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.webkit.URLUtil
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.key.puzzlemodel.config.PuzzleConfig
import com.key.puzzlemodel.databinding.ActivityWebPagePuzzleBinding
import com.key.puzzlemodel.mvvm.BaseMVVMActivity
import com.key.puzzlemodel.mvvm.BaseMVVMViewModel
import com.key.puzzlemodel.util.PuzzleAppManager
import java.net.HttpURLConnection
import java.net.URL


/**
 * @功能描述: 网页长截图 -- 输入网址界面
 * @创建时间: 2021/12/30
 * @创建者: 阳
 * @修改时间: 2021/12/30
 * @修改者: 阳
 *
 * http://www.zyiz.net/tech/detail-62979.html
 */
class InputWebPuzzleActivity :
    BaseMVVMActivity<ActivityWebPagePuzzleBinding, BaseMVVMViewModel>(), View.OnClickListener {
    override val layoutId: Int
        get() = R.layout.activity_web_page_puzzle

    //回调
    var intentActivityResultLauncher: ActivityResultLauncher<Intent>? = null

    override fun initView(savedInstanceState: Bundle?) {
        //添加activity管理
        PuzzleAppManager.getInstance().addActivity(this)

        mVDB.clickListener = this

        findViewById<TextView>(R.id.txt_top_title).text = getString(R.string.page_length_screenshot)
        findViewById<ImageView>(R.id.image_return).setOnClickListener {
            onBackPressed()
        }

//        mVDB.editWeb.setText("https://www.baidu.com/?tn=88093251_84_hao_pg")
//        mVDB.editWeb.setText("https://haokan.baidu.com/v?vid=12275790129908434194&tab=recommend&sfrom=recommend")

        intentActivityResultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                //回调处理
                if (it.resultCode == Activity.RESULT_OK) {
                    it.data?.apply {
                        val mediaPath: String? = getStringExtra(PuzzleConfig.EDIT_RESULT)
                        // Log.e("返回数据：", "InputWebPuzzleActivity == ${getStringExtra(PuzzleConfig.EDIT_RESULT)}")
                        setResult(Activity.RESULT_OK, Intent().apply {
                            putExtra(PuzzleConfig.EDIT_RESULT, mediaPath)
                        })
                        this@InputWebPuzzleActivity.finish()
                    }
                }
            }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.txt_www -> {
                addEditText("www.")
            }
            R.id.txt_com -> {
                addEditText(".com")
            }
            R.id.txt_http -> {
                addEditText("http://")
            }
            R.id.txt_https -> {
                addEditText("https://")
            }
            R.id.btn_next_photo -> { //打开网页

                var webAddress = mVDB.editWeb.text.toString().trim()
//                val webAddress = "https://blog.csdn.net/qq_17806439?spm=1001.2101.3001.5343"
//                val webAddress = "https://www.baidu.com/?tn=88093251_84_hao_pg"

                if (webAddress.isNullOrEmpty()) {
                    Toast.makeText(this, "请输入网址", Toast.LENGTH_SHORT).show()
                    return
                }

                webAddress = getAddressUrl(webAddress)
                mVDB.editWeb.setText(webAddress)

                ///正则表达式判断
                urlToWeb(webAddress)
            }
        }
    }


    /**
     * 在光标处添加文本
     */
    private fun addEditText(addText: String) {

        var index = mVDB.editWeb.selectionStart   // 获取光标所在位置
        var edit = mVDB.editWeb.editableText // 获取EditText的文字
        if (index < 0 || index >= edit.length) {
            edit.append(addText)
        } else {
            // 光标所在位置插入文字
            edit.insert(index, addText)
        }

    }

    /**
     * 输出文本校验
     */
    fun getAddressUrl(strUrl: String): String {

        if (strUrl.startsWith("about:")) return strUrl
        if (strUrl.startsWith("data:")) return strUrl
        if (strUrl.startsWith("file:")) return strUrl
        if (strUrl.startsWith("javascript:")) return strUrl

        var returnAddress = strUrl
        if (!URLUtil.isNetworkUrl(strUrl)) {
            returnAddress = "http://$strUrl"
        }


        return returnAddress
    }

    var handler = object : Handler(Looper.myLooper()!!) {

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
//            Log.e("网址是否可用", "==${msg.what}")

            if (msg.what == 0) {
                val intent = Intent(this@InputWebPuzzleActivity, WebScreenshotsActivity::class.java)
                intent.putExtra("webAddress", mVDB.editWeb.text.toString().trim())
                intentActivityResultLauncher?.launch(intent)
            } else {
                Toast.makeText(this@InputWebPuzzleActivity, "请输入正确的网址", Toast.LENGTH_SHORT).show()
            }

        }
    }

    fun urlToWeb(address: String) {

        Thread(Runnable {
            try {
                val url = URL(address)
                val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
                conn.useCaches = false
                conn.instanceFollowRedirects = true
                conn.connectTimeout = 5000
                conn.readTimeout = 5000
                try {
                    conn.connect()
                } catch (e: Exception) {
                    handler.sendEmptyMessage(-2)
                    e.printStackTrace()
                }
                var code: Int = conn.responseCode

                if (code < 400) {
                    handler.sendEmptyMessage(0)
                } else {
                    handler.sendEmptyMessage(-1)
                }
            } catch (e: Exception) {
                handler.sendEmptyMessage(-2)
                e.printStackTrace()
            }
        }).start()
    }


}

